package debby.bdmap.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import debby.baidumap.R
import android.util.TypedValue


/**
 * Created by debby on 2018/8/6.
 * 描述:
 */
class TitleView : View {
    /**
     * 文本
     */
    private var mTitleText: String? = null
    /**
     * 文本的颜色
     */
    private var mTitleTextColor: Int = 0
    /**
     * 文本的大小
     */
    private var mTitleTextSize: Int = 0

    /**
     * 绘制时控制文本绘制的范围
     */
    private var mBound: Rect? = null
    private var mPaint = Paint()


    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        /**
         * 获得我们所定义的自定义样式属性
         */
        val a = context!!.theme.obtainStyledAttributes(attrs,
                R.styleable.CustomTitleView, defStyleAttr, 0);
        val n = a.indexCount
        for (i in 0 until n) {
            val attr = a.getIndex(i)
            when (attr) {
                R.styleable.CustomTitleView_titleText ->
                    mTitleText = a.getString(attr)
                R.styleable.CustomTitleView_titleTextColor ->
                    // 默认颜色设置为黑色
                    mTitleTextColor = a.getColor(attr, Color.BLACK)
                R.styleable.CustomTitleView_titleTextSize ->
                    // 默认设置为16sp，TypeValue也可以把sp转化为px
                    mTitleTextSize = a.getDimensionPixelSize(attr, TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_SP, 16f, resources.displayMetrics).toInt())
            }
        }
        a.recycle()

        /**
         * 获得绘制文本的宽和高
         */
        mPaint.textSize = mTitleTextSize.toFloat()
        // mPaint.setColor(mTitleTextColor);
        mBound = Rect()
        mPaint.getTextBounds(mTitleText, 0, mTitleText!!.length, mBound)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        mPaint.color = Color.YELLOW;
        canvas!!.drawRect(0F, 0F, getMeasuredWidth().toFloat(), getMeasuredHeight().toFloat(), mPaint)
        mPaint.color = mTitleTextColor;
        canvas.drawText(mTitleText, (width / 2 - mBound!!.width() / 2).toFloat()
                , (height / 2 + mBound!!.height() / 2).toFloat(), mPaint);
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }
}